import Taro, { useReachBottom } from "@tarojs/taro";
import { useState, useEffect } from "react";
import { View, Text, Image } from "@tarojs/components";
import { AtButton, AtAvatar } from "taro-ui";
import Card from "@/components/Card";
import Login from '@/components/Login';
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/avatar.scss";
import { showVolunteerData } from '@/api/my';
import { xiugai, zb, sc, renzheng, noactivity } from "./image.js";

import css from "./index.module.less";

export default function My() {
  const [userInfo, setUserInfo] = useState({});
  // 是否认证
  const [isCertification, setIsCertification] = useState(false);
  // 是否有活动
  const [isActivity, setIsActivity] = useState(false);
  //是否登录
  const [isLogin, setIsLogin] = useState(false);
  //登录所需数据
  const [modalOpen, setModalOpen] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState("");
  const [name, setName] = useState("点击登录/注册");
  useEffect(() => {
    Taro.checkSession({
      success: function () {
        //session_key 未过期，并且在本生命周期一直有效
        Taro.getStorage({
          key: 'userInfo',
          success: function (a) {
            setUserInfo(a.data);
          },
          fail: function () {
            Taro.login(); //重新登录
            setModalOpen(true);
          }
        });
      },
      fail: function () {
        // session_key 已经失效，需要重新执行登录流程
        Taro.login(); //重新登录
        setModalOpen(true);
      }
    });
  }, []);
  const [volunteerData, setVolunteerData] = useState([]);
  const [pageData, setPageData] = useState({ page: 1, pageSize: 5 });
  useEffect(() => {
    showVolunteerData({ page: 1, pageSize: 5 }).then((res) => {
      if (res.code === 200) {
        const data = res.data;
        setVolunteerData(data);
        if (data.length !== 0) {
          setIsActivity(true);
        }
      }
    });
  }, []);
  useReachBottom(() => {
    setPageData({ page: pageData.page + 1, pageSize: pageData.pageSize });
    showVolunteerData(pageData).then((res) => {
      if (res.data.length > 0) {
        const newData = volunteerData.concat(res.data);
        setVolunteerData(newData);
      }
    });
  });

  //出现登录注册弹窗
  const goLoginRegister = () => {
    Taro.getStorage({
      key: 'userInfo',
      success: function (res) {
        if (!("id" in userInfo)) {
          setUserInfo(res.data);
          setIsLogin(true);
        }
      },
      fail: function () {
        if (name === "点击登录/注册") setModalOpen(true);
      }
    });
  };

  useEffect(() => {
    if ("id" in userInfo) {
      setAvatarUrl(userInfo.avatarurl);
      setName(userInfo.nickname);
      setIsLogin(true);
      if (isLogin) {
        setIsCertification(userInfo.isAudited === 1 ? true : false);
        // setIsActivity(userInfo.isAudited === 1 ? true : false);
      }
    }
  }, [name, avatarUrl, userInfo, isLogin]);

  const updateLogin = () => {
    Taro.getStorage({
      key: 'userInfo',
      success: function (res) {
        if (res.data.isAudited) {
          setIsCertification(true);
          return true;
        }
        return false;
      }
    });
  };

  const authorized = () => {
    if (updateLogin()) Taro.navigateTo({ url: "myInfo/index" });
    else Taro.navigateTo({ url: "certification/index" });
  };
  const goMyInfo = () => {
    Taro.navigateTo({ url: "myInfo/index" });
  };
  const toMyBranch = () => {
    if (isCertification) Taro.navigateTo({ url: "branch/index" });
    else authorized();
  };
  const toMyCollection = () => {
    if (isCertification) Taro.navigateTo({ url: "collection/index" });
    else authorized();
  };
  return (
    <View className={css.app}>
      <View className={css.header}>
        <View className={css.content}>
          <AtAvatar circle image={avatarUrl} className={css.image}></AtAvatar>
          <View className={css.info}>
            <Text className={css.name} onClick={goLoginRegister}>{name}</Text>
            <Text className={css.life}>我的生活组织</Text>
          </View>

          {!isLogin ? '' : isCertification ? (
            <AtButton
              type='secondary'
              size='small'
              circle
              className={css.setting}
              onClick={goMyInfo}
            >
              <View>
                <Image src={xiugai} className={css.image} />
                <Text>个人信息修改</Text>
              </View>
            </AtButton>
          ) : (
            <AtButton
              type='secondary'
              size='small'
              circle
              className={css.setting}
              onClick={authorized}
              disabled={isLogin ? false : true}
            >
              <View>
                {" "}
                <Image src={renzheng} className={css.image} />
                身份认证
              </View>
            </AtButton>
          )}

        </View>
        <View className={css.bottom}>
          <View className={css.box} onClick={isLogin ? toMyBranch : goLoginRegister}>
            <Image src={zb} style={{ marginTop: '2px' }} />
            <Text className={css.text}>我的支部</Text>
          </View>
          <View className={css.box} onClick={isLogin ? toMyCollection : goLoginRegister}>
            <Image src={sc} />
            <Text className={css.text}>我的收藏</Text>
          </View>
        </View>
      </View>
      <View className={css.content}>
        {isActivity ? (
          <View>
            {volunteerData === [] ? '' : volunteerData.map((v) => {
              return (<View key={v.id}>
                <Card info={{ text: v.activityTitle, date: v.activityTime, school: v.organizationName, state: v.activityState }} />
              </View>);
            })}
          </View>
        ) : (
          <View className={css.noactivity}>
            <Image src={noactivity} />
          </View>
        )}
      </View>

      <Login modalOpen={modalOpen} setModalOpen={setModalOpen} setName={setName} setAvatarUrl={setAvatarUrl} setIsLogin={setIsLogin} />
    </View>
  );
}
